package com.example.demo.db;

import com.example.demo.db.base.CommonShardDataBase;
import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

/**
 * @author ricky
 * @date 2022/1/28
 */
public class DefaultTableRangeShardingAlgorithm extends CommonShardDataBase implements RangeShardingAlgorithm<Date> {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> rangeShardingValue) {
        Range<Date> ranges = rangeShardingValue.getValueRange();
        String logicTableName = rangeShardingValue.getLogicTableName();

        Calendar startInstance = Calendar.getInstance();
        startInstance.setTime(ranges.lowerEndpoint());
        Calendar endInstance = Calendar.getInstance();
        endInstance.setTime(ranges.upperEndpoint());

        int startYear = startInstance.get(Calendar.YEAR);
        int endYear = endInstance.get(Calendar.YEAR);


        Collection<String> tables = new LinkedHashSet<>();

        for (int i = startYear; i <= endYear; i++) {
            tables.add(logicTableName + "_" + i);
        }
        return tables;
    }
}
